﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class ShakeForm : Form
    {
        [DllImport("user32.dll")]
        static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        private Button shakeBtn;

        public ShakeForm()
        {
            InitializeForm();
            InitializeComponents();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void InitializeForm()
        {
            this.Text = "窗口抖动效果";
            this.Size = new Size(300, 200);
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void InitializeComponents()
        {
            shakeBtn = new Button
            {
                Text = "摇动窗口!",
                Size = new Size(120, 50),
                Location = new Point(80, 60),
                Font = new Font("Arial", 12)
            };
            shakeBtn.Click += ShakeBtn_Click;
            this.Controls.Add(shakeBtn);
        }

        public void ShakeWindow()
        {
            GetWindowRect(this.Handle, out RECT original);
            Random rnd = new Random();

            for (int i = 0; i < 20; i++)
            {
                this.Location = new Point(
                    original.Left + rnd.Next(-15, 15),
                    original.Top + rnd.Next(-10, 10)
                );
                Thread.Sleep(30);
                Application.DoEvents();
            }
            this.Location = new Point(original.Left, original.Top);
        }

        private void ShakeBtn_Click(object sender, EventArgs e)
        {
            new Thread(ShakeWindow).Start();
        }

        //[STAThread]
        //static void Main()
        //{
        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);
        //    Application.Run(new ShakeForm());
        //}
    }
}